﻿using SUNRPA.CONTROLS.IMPL.domain;
using SUNRPA.CONTROLS.IMPL.domain.flowItemParam;
using System.Collections.Concurrent;
using Microsoft.Office.Interop.Excel;
using SUNRPA.CONTROLS.IMPL.util;
using SUNRPA.CONTROLS.IMPL.domain.flowRunningVar;

namespace SUNRPA.CONTROLS.IMPL.controls {
    public class CopyPivotTableNAction:BaseControlActions {
        public override int Execute(int currentIndex, FlowItem item, ConcurrentDictionary<string, ConcurrentDictionary<string, RPAVariableDefineWrapper>> globleData, List<FlowItem> flowItems) {
            CopyPivotTableNParam? param = item.ControlParam as CopyPivotTableNParam;
            string sourceObject = param.SourceObject;
            Workbook sourceWb = this.GetObjVar<ExcelModel>(ref sourceObject, globleData).WorkBookValue as Workbook;
            if(sourceWb == null) { 
                throw new RpaRuntimeException(String.Format("Excel对象{0}不存在", sourceObject));
            }

            string targetObject = param.TargetObject;
            Workbook targetWb = this.GetObjVar<OtherModel>(ref targetObject, globleData).Value as Workbook;
            if(targetWb == null) { 
                throw new RpaRuntimeException(String.Format("Excel对象{0}不存在", targetObject));
            }

            ExcelUtil sourceExcel = new ExcelUtil();
            sourceExcel.SetApp(sourceWb);

            ExcelUtil targetExcel = new ExcelUtil();
            targetExcel.SetApp(targetWb);

            string sourceSheet = param.SourceSheet;
            this.GetStringVar(ref sourceSheet, globleData);
            string targetSheet = param.TargetSheet;
            this.GetStringVar(ref targetSheet, globleData);

            int copyType = param.CopyType;
            string rowString = param.TargetRow;
            string columnString = param.TargetColumn;
            string pivotNameOrIndex = param.SourceNameOrIndex;

            this.GetStringVar(ref rowString, globleData);
            this.GetStringVar(ref columnString, globleData);
            this.GetStringVar(ref pivotNameOrIndex, globleData);

            int rowNum = targetExcel.GetRowNum(rowString, targetSheet);
            int columnNum = targetExcel.GetColumnNum(columnString, targetSheet);

            sourceExcel.CopyPivotTable(pivotNameOrIndex, sourceSheet);
            targetExcel.PastePivotTable(targetSheet, rowNum, columnNum, copyType);
            return currentIndex;
        }
    }
}
